package com.gzittc.gzgm.gm.model.db.DBHelper;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.gzittc.gzgm.gm.model.db.bean.PDSubject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yzc on 2017-12-16.
 */

public class DBHelper {

    Context context;

    private SQLiteDatabase db;

    //数据库的名称
    private String DB_NAME = "title.db";
    //数据库的地址
    private String DB_PATH = "/data/data/com.gzittc.gzgm/databases/";

    //    获取数据库的数据
    public List<PDSubject> getPDQuestion() {
        List<PDSubject> list = new ArrayList<>();
        //执行sql语句
        Cursor cursor = db.rawQuery("select * from PDTest", null);
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            int count = cursor.getCount();
            //遍历
            for (int i = 0; i < count; i++) {
                cursor.moveToPosition(i);
                PDSubject pdBean = new PDSubject();
                pdBean.setMain_title(cursor.getString(cursor.getColumnIndex("MainTitle")));//题目内容
                pdBean.setA(cursor.getString(cursor.getColumnIndex("A")));//A答案
                pdBean.setB(cursor.getString(cursor.getColumnIndex("B")));//B答案
                pdBean.setAnswer(cursor.getString(cursor.getColumnIndex("Answer")));//正确答案
                pdBean.setMain_title_len(cursor.getInt(cursor.getColumnIndex("MaintitleLen")));//题目的长度

                list.add(pdBean);
            }
        }
        return list;
    }

    //构造方法
    public DBHelper() {
        //连接数据库
    }

    public DBHelper(Context context){
        this.context = context;
        initFile();
        db = SQLiteDatabase.openDatabase("/data/data/com.gzittc.gzgm/databases/title.db", null, SQLiteDatabase.OPEN_READWRITE);
    }

    private void initFile(){
        //判断数据库是否拷贝到相应的目录下
        if (new File(DB_PATH + DB_NAME).exists() == false) {
            File dir = new File(DB_PATH);
            if (!dir.exists()) {
                dir.mkdir();
            }

            //复制文件
            try {
                InputStream is = context.getAssets().open(DB_NAME);
                OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);

                //用来复制文件
                byte[] buffer = new byte[1024];
                //保存已经复制的长度
                int length;

                //开始复制
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }

                //刷新
                os.flush();
                //关闭
                os.close();
                is.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
